import router from '@/router/index'
import pinia from '@/store/index'
import baseData from '@/store/baseData'
import qs from 'qs'
router.beforeEach(async (to, from, next) => {
  console.log('router.beforeEach', to, from)
  // 获取字典数据 做初始化
  const baseDataStore = baseData(pinia)
  if (!Object.keys(baseDataStore.flattenDictData).length) {
    await baseDataStore.setFlattenDictData()
  }
  // 获取主题颜色
  const theme = qs.parse(window.location.href.split('?')[1]).theme
  theme && baseDataStore.updatedThemeName(theme)
  next()
})

/**
 * @description 监听路由错误，正则匹配对应的错误消息后，自动刷新界面
 * 解决前端发版出现-跳转路由页面加载该页面js文件404时，触发router.onError的场景
 */
router.onError((error) => {
  console.log('router-error', error)
  const pattern = /Loading chunk chunk-(.*)+ failed/g
  const isChunkLoadFailed = error.message.match(pattern)
  if (isChunkLoadFailed) {
    location.reload()
  }
})
